package com.example.shop_car_2208.comment

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.shop_car_2208.R
import com.example.shop_car_2208.adapter.CommentAdapter
import com.example.shop_car_2208.databinding.ActivityCommentBinding
import com.example.shop_car_2208.mvvm.BaseActivity

@Route(path = "/app/comment")
class CommentActivity : BaseActivity<ActivityCommentBinding,CommentViewModel>() {
    lateinit var commentAdapter: CommentAdapter
    var index = 0
    override fun initData() {
        viewModel.CommentSuccess.observe(this){
            if (it.code == 200){
                commentAdapter.data.clear()
                commentAdapter.data.addAll(it.data)
                commentAdapter.notifyDataSetChanged()
            }
        }
        viewModel.getchildSuccess.observe(this){
            if (it.code == 200){
                commentAdapter.data.addAll(index,it.data)
                commentAdapter.notifyDataSetChanged()
            }
        }
        viewModel.HUIFUCommentSuccess.observe(this){
            if (it.code == 200){
                commentAdapter.data.add(index,it.data[0])
                commentAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initView() {
        commentAdapter = CommentAdapter()
        binding.rvComment.adapter = commentAdapter
        binding.rvComment.layoutManager =  LinearLayoutManager(this)
        viewModel.getComment()

        commentAdapter.addChildClickViewIds(R.id.comment_more,R.id.comment_add)
        commentAdapter.setOnItemChildClickListener { adapter, view, position ->

            when(view.id){
                R.id.comment_more->{
                    viewModel.getChild(commentAdapter.data[position].rootid)
                    index = position//记录当前点击的小标为
                }
                R.id.comment_add->{
                    viewModel.getHFComment(binding.etComment.text.toString(),commentAdapter.data[position].id)
                    index = position
                    binding.etComment.setText(null)
                }
            }
        }
        //点击发送按钮，实现发送评论
        binding.btnComment.setOnClickListener {
            val msg = binding.etComment.text.toString()
            viewModel.getComment(msg)

            viewModel.ttCommentSuccess.observe(this){
                if (it.code == 200){
                    commentAdapter.data.add(0,it.data[0])
                    commentAdapter.notifyDataSetChanged()
                }
            }
            binding.etComment.setText(null)

        }


    }

    override fun getViewModel(): Class<CommentViewModel> {
        return CommentViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.activity_comment
    }



}